package design_pattern.ThreadLocal;

import java.util.Random;

/**
 * @Author: 蔡翔
 * @Date: 2019/11/11 11:16
 * @Version 1.0
 *
 * （重要）线程保险箱 ThreadLocal<T> 这个很有用
 * 核心：你存进去的数据 一定是以 当前Key 为value的。
 */
public class ThreadLocalComplexTest {
    //这个是自定义的,,ThreadLocalSimulator<String>这里的String意思就是 ThreadLocalSimulator 里面的T类型都是 String
    //new ThreadLocalSimulator<>() 后面加{} 代表要重写 ThreadLocalSimulator类里面的方法
    private static final ThreadLocalSimulator<String> threadSimulator = new ThreadLocalSimulator<String>(){
        @Override
        public String initualValue() {
            return "No Value";
        }
    };
    //这个是 官方的。
    private static final ThreadLocal<String> threadLocal = new ThreadLocal<>();

    //seed
    private static final Random random = new Random(System.currentTimeMillis());

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            threadLocal.set("Thread1");
            try {
                Thread.sleep(random.nextInt(1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " " + threadLocal.get());
        }, "Thread1");

        Thread thread1 = new Thread(() -> {
            threadLocal.set("Thread2");
            threadLocal.set("Thread22");  // 取出的内容是最后 一次存入的。
            try {
                Thread.sleep(random.nextInt(1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " " + threadLocal.get());
        }, "Thread2");

        thread.start();
        thread1.start();
        thread.join();
        thread1.join();

        System.out.println("========================");
        System.out.println("在main 线程中取 上面两个线程 set 的内容"+threadLocal.get());
    }
}
